#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define COUNT_TEST 10
#define BUFFER_SIZE 1<<11

char** inputs;
char** outputs;

int
cmp (const void *a, const void *b)
{
  
  return (*(int *) a - *(int *) b);
}

void write_file(char* filename, int* array, int array_length){
  FILE *pf;
  pf=fopen(filename,"w");
  int i;
  for (i = 0; i < array_length; i++)
    fprintf(pf,"%d,",array[i]);

  fclose(pf);
}

void generate_array(int max_count, int max_number, int test_number){
  int* array = malloc(max_count*sizeof(int));
  int i;
  for (i = 0; i < max_count; i++){
    array[i] = rand()%max_number;
    if ((rand() % 2) == 0)
      array[i] = -array[i];
  }

  write_file(inputs[test_number],array,max_count);

  qsort (array, max_count, sizeof (int), cmp);

  write_file(outputs[test_number],array,max_count);
  free(array);
}

void make_filenames(){
  inputs = malloc (COUNT_TEST*sizeof(char*));
  outputs = malloc (COUNT_TEST*sizeof(char*));
  int i;
  for (i = 0; i < COUNT_TEST; ++i){
    inputs[i] = (char *) malloc (20 * sizeof (char));
    outputs[i] = (char *) malloc (20 * sizeof (char));
    sprintf (inputs[i], "tests/input%d.csv", i);
    sprintf (outputs[i], "tests/output%d.csv", i);
  }


}
void finalize(){
  int i;
  for (i = 0; i < COUNT_TEST; ++i){
    free (inputs[i]);
    free (outputs[i]);
  }
  free(inputs);
  free(outputs);

}

int
check_files (){
	 int i;
	 for (i = 0; i < COUNT_TEST; ++i)
	   {
		    run_program ("./sort", "sort", inputs[i], "output");
		    run_program ("diff", "diff", outputs[i], "output");
	   }
}

void
run_program (char *program_path, char *program, char *input, char *output){

	 int pipefd[2];
	 pipe (pipefd);

	 int pid = fork ();
	 if (pid == 0)
	   {
		    close (pipefd[0]);
		    dup2 (pipefd[1], 1);
		    dup2 (pipefd[1], 2);
		    close (pipefd[1]);

		    if (execlp(program_path, program, input, output,(char *) 0) < 0)
		      {
			       perror (program);
			       exit (1);
		      }
	   }
	 else
	   {
		    char buffer[BUFFER_SIZE];
		    close (pipefd[1]);
		    int count = read (pipefd[0], buffer, sizeof (buffer));
		    wait (pid);
		    if (strcmp (program, "diff") == 0)
          printf (count !=0 ? "TEST %s ERROR\n" : "TEST %s    PASSED\n", input, input);

	   }
}

int
main (int argc, char *argv)
{
  make_filenames();
  int i;
  for (i = 0; i < COUNT_TEST; ++i){
    generate_array(10<<i,10<<i,i);
  }
 finalize();
}
